package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.MealScheduleDAO;
import com.neusoft.EYSystem.dao.MealitemDAO;
import com.neusoft.EYSystem.dao.MealpickDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.MealScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MealScheduleServiceImpl implements MealScheduleService {

    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    private MealScheduleDAO mealScheduleDAO;
    @Autowired
    private MealitemDAO mealitemDAO;
    @Autowired
    private MealpickDAO mealpickDAO;

    @Override
    public ResponseBean<Integer> addMealSchedule(MealSchedule mealSchedule, Mealitem mealitem) {
        ResponseBean<Integer> response = new ResponseBean<>();

        // 1. 查时间段
        QueryWrapper<MealSchedule> wrapperSchedule = new QueryWrapper<>();
        wrapperSchedule.eq("day", mealSchedule.getDay());
        wrapperSchedule.eq("meal", mealSchedule.getMeal());
        MealSchedule mealSchedule1 = mealScheduleDAO.selectOne(wrapperSchedule);

        if (mealSchedule1 == null) {
            response.setStatus(400);
            response.setMsg("未找到对应的时间段（" + mealSchedule.getDay() + " " + mealSchedule.getMeal() + "）");
            return response;
        }

        // 2. 查菜品
        QueryWrapper<Mealitem> wrapperItem = new QueryWrapper<>();
        wrapperItem.eq("name", mealitem.getName());
        Mealitem mealitem1 = mealitemDAO.selectOne(wrapperItem);

        if (mealitem1 == null) {
            response.setStatus(400);
            response.setMsg("菜品不存在：" + mealitem.getName());
            return response;
        }

        // 3. 防重复
        QueryWrapper<Mealpick> wrapperPick = new QueryWrapper<>();
        wrapperPick.eq("schedule_id", mealSchedule1.getScheduleId())
                .eq("mealitem_id", mealitem1.getMealitemId()).eq("status", "2");
        if (mealpickDAO.selectOne(wrapperPick) != null) {
            response.setStatus(400);
            response.setMsg("该菜品已在该时间段中，不能重复添加");
            return response;
        }

        // 4. 构造 Mealpick 插入
        Mealpick mealpick = new Mealpick();
        mealpick.setScheduleId(mealSchedule1.getScheduleId());
        mealpick.setMealitemId(mealitem1.getMealitemId());
        mealpick.setStatus("2"); // 日历启用标记

        try {
            if (mealpickDAO.insert(mealpick) > 0) {
                response.setStatus(200);
                response.setMsg("膳食日历添加成功");
            } else {
                response.setStatus(400);
                response.setMsg("膳食日历添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("膳食日历添加失败：" + e.getMessage());
        }

        return response;
    }

    @Override
    public PageResponseBean<List<MealScheduleAndItemAndPick>> pageMealSchedule(
            Long cur, Long number, MealSchedule mealSchedule, Mealitem mealitem) {

        List<MealScheduleAndItemAndPick> fullList = new ArrayList<>();

        // 1. 查询符合 day / meal 的 schedule 列表
        QueryWrapper<MealSchedule> wrapperSchedule = new QueryWrapper<>();
        if (isValid(mealSchedule.getDay())) {
            wrapperSchedule.eq("day", mealSchedule.getDay());
        }
        if (isValid(mealSchedule.getMeal())) {
            wrapperSchedule.eq("meal", mealSchedule.getMeal());
        }

        List<MealSchedule> allSchedules = mealScheduleDAO.selectList(wrapperSchedule);

        for (MealSchedule schedule : allSchedules) {
            // 2. 查找 status = 2 / 3 的 pick
            QueryWrapper<Mealpick> wrapperPick = new QueryWrapper<>();
            wrapperPick.eq("schedule_id", schedule.getScheduleId());
            if (isValid(mealitem.getStatus())) {
                // 如果传入的 mealitem.status 不为空，则按该状态查询
                wrapperPick.eq("status", mealitem.getStatus());
            } else {
                // 否则查询 status 为 2 或 3 的
                wrapperPick.in("status", Arrays.asList("2", "3"));
            }

            List<Mealpick> picks = mealpickDAO.selectList(wrapperPick);

            if (picks.isEmpty()) continue;

            List<Integer> itemIds = picks.stream()
                    .map(Mealpick::getMealitemId)
                    .toList();

            List<Mealitem> items;
            if (isValid(mealitem.getName())) {
                QueryWrapper<Mealitem> itemWrapper = new QueryWrapper<>();
                itemWrapper.in("mealitem_id", itemIds);
                itemWrapper.like("name", mealitem.getName()); // 模糊匹配菜品名
                items = mealitemDAO.selectList(itemWrapper);
            } else {
                items = mealitemDAO.selectBatchIds(itemIds);
            }

            // 建立 mealitemId -> Mealitem 映射，加速查找
            Map<Integer, Mealitem> itemMap = items.stream()
                    .collect(Collectors.toMap(Mealitem::getMealitemId, m -> m));

            // 组装结果
            for (Mealpick pick : picks) {
                Mealitem item = itemMap.get(pick.getMealitemId());
                if (item == null) continue;

                MealScheduleAndItemAndPick result = new MealScheduleAndItemAndPick();
                result.setMealSchedule(schedule);
                result.setMealitem(item);
                result.setMealpick(pick);
                fullList.add(result);
            }
        }

        // 3. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), fullList.size());
        List<MealScheduleAndItemAndPick> pageList =
                fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : List.of();

        // 4. 封装返回
        PageResponseBean<List<MealScheduleAndItemAndPick>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(fullList.size());
        return rb;
    }

    @Override
    public PageResponseBean<List<MealScheduleAndItemAndPick>> pageMealScheduleBystuts(Long cur, Long number, MealSchedule mealSchedule, Mealitem mealitem) {
        List<MealScheduleAndItemAndPick> fullList = new ArrayList<>();

        // 1. 查询符合 day / meal 的 schedule 列表
        QueryWrapper<MealSchedule> wrapperSchedule = new QueryWrapper<>();
        if (isValid(mealSchedule.getDay())) {
            wrapperSchedule.eq("day", mealSchedule.getDay());
        }
        if (isValid(mealSchedule.getMeal())) {
            wrapperSchedule.eq("meal", mealSchedule.getMeal());
        }

        List<MealSchedule> allSchedules = mealScheduleDAO.selectList(wrapperSchedule);

        for (MealSchedule schedule : allSchedules) {
            // 2. 查找 status = 2  的 pick
            QueryWrapper<Mealpick> wrapperPick = new QueryWrapper<>();
            wrapperPick.eq("schedule_id", schedule.getScheduleId());
            wrapperPick.in("status", Arrays.asList("2"));
            List<Mealpick> picks = mealpickDAO.selectList(wrapperPick);

            if (picks.isEmpty()) continue;

            List<Integer> itemIds = picks.stream()
                    .map(Mealpick::getMealitemId)
                    .toList();

            List<Mealitem> items;
            if (isValid(mealitem.getName())) {
                QueryWrapper<Mealitem> itemWrapper = new QueryWrapper<>();
                itemWrapper.in("mealitem_id", itemIds);
                itemWrapper.like("name", mealitem.getName()); // 模糊匹配菜品名
                items = mealitemDAO.selectList(itemWrapper);
            } else {
                items = mealitemDAO.selectBatchIds(itemIds);
            }

            // 建立 mealitemId -> Mealitem 映射，加速查找
            Map<Integer, Mealitem> itemMap = items.stream()
                    .collect(Collectors.toMap(Mealitem::getMealitemId, m -> m));

            // 组装结果
            for (Mealpick pick : picks) {
                Mealitem item = itemMap.get(pick.getMealitemId());
                if (item == null) continue;

                MealScheduleAndItemAndPick result = new MealScheduleAndItemAndPick();
                result.setMealSchedule(schedule);
                result.setMealitem(item);
                result.setMealpick(pick);
                fullList.add(result);
            }
        }

        // 3. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), fullList.size());
        List<MealScheduleAndItemAndPick> pageList =
                fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : List.of();

        // 4. 封装返回
        PageResponseBean<List<MealScheduleAndItemAndPick>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(fullList.size());
        return rb;
    }


}
